package role

import (
	"context"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RoleMenuActionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRoleMenuActionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleMenuActionListLogic {
	return &RoleMenuActionListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RoleMenuActionListLogic) RoleMenuActionList(req *types.RoleMenuActionListRo) (resp *types.RoleMenuActionListRsp, err error) {
	var roleMenuActions []model.RoleMenuAction
	if err := l.svcCtx.DB.WithContext(l.ctx).Where("RoleId=?", req.RoleId).
		Find(&roleMenuActions).Error; err != nil {
		return nil, err
	}
	resp = new(types.RoleMenuActionListRsp)

	var menus = make(map[int][]int)
	for _, v := range roleMenuActions {
		if _, ok := menus[v.MenuId]; !ok {
			menus[v.MenuId] = make([]int, 0)
		}
		menus[v.MenuId] = append(menus[v.MenuId], v.ActionId)
	}

	resp = new(types.RoleMenuActionListRsp)
	for k, v := range menus {
		resp.Items = append(resp.Items, types.MenuAction{
			MenuId:   k,
			ActionId: v,
		})
	}

	return
}
